/*
作者：邓佳雷
效果：DHT11 温湿度测量
版本：1.0
更新时间：2019年11月13日
*/
#include"ESP8266WiFi.h"
#include "DHT.h" //加载DHT11的库
#include <PubSubClient.h>
#include <Adafruit_ssd1306syp.h>

#define wifi_ssid "HUAWEI-354"
#define wifi_password "88888888"
#define mqtt_server "www.bigiot.xyz"
#define mqtt_port 1883
#define mqtt_user "10"
#define mqtt_password "AFrdUloGk"
#define in_topic "user/data"
#define out_topic "deng2016/data"
#define DHTTYPE DHT11 // 定义传感器类似 DHT11
#define DHTPIN D1 //宏定义DHT数据接口，编译时DHTPIN会替换成2
#define led = D2
#define SDA_PIN D5                                            //D8
#define SCL_PIN D6
Adafruit_ssd1306syp display(SDA_PIN,SCL_PIN);
WiFiClient espClient;
PubSubClient client;
DHT dht(DHTPIN, DHTTYPE);//声明 dht 函数

void setup() {
      Serial.begin(9600);
      setup_wifi();
      client.setClient(espClient);
      client.setServer(mqtt_server, mqtt_port);
      client.setCallback(callback);
      dht.begin(); //启动传感器
      display.initialize();
}
void loop() {
   
      if (!client.connected()) {
        reconnect();
      }
      client.loop();
      // Publishes a random 0 and 1 like someone switching off and on randomly (random(2))
      //client.publish(out_topic, String(random(2)).c_str(), true);
      delay(1000);
      client.subscribe(in_topic);
   
      delay(2000); //采样延时，每次抓取数据时间间隔 1~2秒钟
      float h = dht.readHumidity();//读取湿度
      float t = dht.readTemperature();//读取摄氏度   
      if (isnan(h) || isnan(t)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
      } //检查抓取是否成功   
      Serial.print("Humidity: ");
      Serial.print(h);
      Serial.print(" %\t");
      Serial.print("Temperature: ");
      Serial.print(t);
      Serial.println(" *C ");
      //client.publish(out_topic, (String("Humidity:")+String(h)+String(" Temprature:")+String(t)).c_str(), false);
      client.publish(out_topic, (String("{ \"key\":\"temp\", \"vlue\":\"")+String(t)+"\"}").c_str(), false);
      client.publish(out_topic, (String("{ \"key\":\"hum\",  \"vlue\":\"")+String(h)+"\"}").c_str(), false);
      Serial.println(String("{ \"key\":\"temp\", \"vlue\":\"")+20+"\"}");
      display.clear();
      display.setCursor(0,0);
      display.setTextSize(1.5);
      display.setTextColor(WHITE);
      display.println("Hum:"+String(h)+"%");

      display.setCursor(0,30);
      display.setTextSize(1);
      display.setTextColor(WHITE);
      display.println("Tem:"+String(t)+"*C");
      display.update();
      
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);

  WiFi.begin(wifi_ssid, wifi_password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    // If you do not want to use a username and password, change next line to
    // if (client.connect("ESP8266Client")) {
    if (client.connect("deng2016_led", mqtt_user, mqtt_password)) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
 //Serial.print("Message arrived [");
 //Serial.print(topic);
 //Serial.print("] ");
 for (int i = 0; i < length; i++) {
  char receivedChar = (char)payload[i];
 }
}
